var md5 = require('js-md5')
var config = require('../utils/config.js')
let serverAddress = config.serverAddress
let serverUrl = serverAddress.apiSys
import { isBlank, endWith, startWith, getArgs } from '../utils/'
export const fetch = (module, url, method, data) => {
    switch (module) {
        case 'sys':
            serverUrl = serverAddress.apiSys
            break;
        case 'user':
            serverUrl = serverAddress.apiUser
            break;
        case 'mall':
            serverUrl = serverAddress.apiMall
            break;
        case 'order':
            serverUrl = serverAddress.apiOrder
            break;
        default:
            console.error('没有此模块')
    }
    var tempName = endWith(serverUrl, "/") ? serverUrl.substring(0, serverUrl.length - 1) : serverUrl;
    var tempNames = tempName.split("/")
    var projectName = tempNames[tempNames.length - 1]
    var _key = wx.getStorageSync('userId')
    _key = isBlank(_key) ? "" : _key
    if (url.indexOf("?") == -1) {
        url += "?key=" + _key + "&port=app";
    } else {
        url += "&key=" + _key + "&port=app";
    }
    // 请求相对路径
    var requestURI = url.split("?")[0]
    requestURI = startWith(url, "/") ? requestURI : "/" + requestURI;
    requestURI = endWith(url, "/") ? requestURI.substring(0, requestURI.length - 1) : requestURI;
    
    // 请求参数
    var args = getArgs(url)
    args = args.sort((a,b) => {
        return a.key > b.key ? 1 : -1
    })
    var paramsString = ""
    args.forEach(v => {
        paramsString += v.key + v.value
    })
    var _secret = wx.getStorageSync('appsecret') || ''
    var sign = md5(_secret+"/" + projectName + requestURI + paramsString)
    return new Promise((resolve, reject) => {
        try {
            wx.request({
                module,
                url: serverUrl + url + "&sign=" +sign,
                method,
                data,
                header: {
                    'content-type': 'application/json'
                },
                success(res) {
                    resolve(res.data)
                },
                fail(e) {
                    reject(e)
                }
            })
        } catch (e) {
            console.error("error" + e)
        }
    })
}